package com.stox.ui.javafx.charting.event.handler;

import java.util.List;

import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;

import com.stox.ui.javafx.charting.model.plot.AbstractPrimaryPlot;
import com.stox.ui.javafx.charting.model.uiunit.AbstractPrimaryUiUnit;
import com.stox.ui.javafx.charting.widget.ResizableCanvas;
import com.stox.ui.javafx.charting.widget.axis.InformationAxis;

public class InformationAxisMouseMovedEventHandler implements EventHandler<MouseEvent> {

	public static final InformationAxisMouseMovedEventHandler instance = new InformationAxisMouseMovedEventHandler();

	private InformationAxisMouseMovedEventHandler() {
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void handle(MouseEvent event) {
		if(MouseEvent.MOUSE_MOVED.equals(event.getEventType())) {
			double x = event.getX();
			if(!(event.getSource() instanceof ResizableCanvas)) return;
			ResizableCanvas canvas = (ResizableCanvas)event.getSource();
			AbstractPrimaryPlot plot = canvas.getChart().getChartingView().getPrimaryChart().getFrontPlot();
			if(null == plot) return;
			List<AbstractPrimaryUiUnit> uiUnits = plot.getUiUnits();
			if(null == uiUnits || uiUnits.isEmpty()) return;
			
			int low = 0;
			int high = uiUnits.size()-1;
			AbstractPrimaryUiUnit uiUnit = null;
			while (low <= high) {
	            int mid = (low + high) >>> 1;
	            AbstractPrimaryUiUnit midVal = uiUnits.get(mid);
	            
	            if((midVal.getX() + midVal.getWidth()) < x)
	            	high = mid - 1;
	            else if(midVal.getX() > x)
	            	low = mid + 1;
	            else {
	            	uiUnit = midVal;
	            	break;
	            }
			}
			
			if(null == uiUnit) return;
			InformationAxis informationAxis = (InformationAxis)canvas.getChart().getChartingView().getPrimaryChart().getTopHorizontalAxis();
			if(null == informationAxis) return;
			informationAxis.setUiUnit(uiUnit);
			informationAxis.update();
		}
	}

}
